package megacli

import (
    "fmt"
    "github.com/prometheus/common/log"
    "math"
    "os"
    "strconv"
    "strings"
)

// 判断文件是否存在
func Exists(path string) bool {
    _, err := os.Stat(path)
    return err == nil
}

// 通过字符串长度对块设备进行排序
func BlkLabelAscSorter(a, b string) bool {
    if len(a) == len(b) {
        return a < b
    }
    return len(a) < len(b)
}

// 获取megacli命令行
func scanPathList(list []string) (string, error) {
    for _, l := range list {
        if Exists(l) {
            return l, nil
        }
    }
    return "", fmt.Errorf("can not find megacli")
}

// 解析键值对
func SplitKeyVal(line, delim string) (key string, val string, err error) {
    log.Debug(line)
    l := strings.TrimSpace(line)
    if l == "" {
        err = fmt.Errorf("empty line")
        return
    }

    if !strings.Contains(l, delim) {
        err = fmt.Errorf("line has no '%s'", delim)
        return
    }

    flds := strings.SplitN(l, delim, 2)
    if len(flds) != 2 {
        err = fmt.Errorf("invalid format")
        return
    }

    key = strings.TrimSpace(flds[0])
    val = strings.TrimSpace(flds[1])

    return
}

// 计数单位
func GetMultiplier(val string, base Base) float64 {
    b := float64(base)

    if strings.Contains(val, "KB") {
        return math.Pow(b, 1)
    }
    if strings.Contains(val, "MB") {
        return math.Pow(b, 2)
    }
    if strings.Contains(val, "GB") {
        return math.Pow(b, 3)
    }
    if strings.Contains(val, "TB") {
        return math.Pow(b, 4)
    }
    if strings.Contains(val, "PB") {
        return math.Pow(b, 5)
    }
    if strings.Contains(val, "EB") {
        return math.Pow(b, 6)
    }
    return 0
}

// ShapeSpacedString returns shaped string which is remoeved multiple spaces
// e.g:
// Before: 7JJ7W7GCHUH721010ALE600                         T281
// After:  7JJ7W7GCHUH721010ALE600 T281
func ShapeSpacedString(val string) string {
    flds := strings.Fields(val)
    return strings.Join(flds, " ")
}

// ParseSize returns unsigned integer value from given string with unit and base
func ParseSize(val string, base Base) uint64 {
    flds := strings.Fields(val)
    if len(flds) == 0 {
        return 0
    }
    size, err := strconv.ParseFloat(flds[0], 64)
    if err != nil {
        return 0
    }

    return uint64(size * GetMultiplier(val, base))
}